<template>
    <el-scrollbar height="70vh" width="100%">
        <el-descriptions
                :title="data?.taskName + '--解析协议'"
                :border="true"
                :column="2"
                label-width="20%"
        >
            <template #extra>
                <el-button
                        :icon="dataResolver.flag ? Edit : Plus"
                        type="primary"
                        @click="openDialog"
                >{{ dataResolver.flag ? "修改" : "新增" }}
                </el-button
                >
            </template>
            <el-descriptions-item
                v-if="dataResolver.flag"
                label="名称"
                align="center"
            >
                <div>{{ dataResolver.data.name }}</div>
            </el-descriptions-item>
            <el-descriptions-item
                    v-if="dataResolver.flag"
                    label="状态"
                    align="center"
            >
                <el-tag
                        :style="{ marginRight: '6px' }"
                        :type="dataResolver.data.status ? 'success' : 'info'"
                >{{ dataResolver.data.status ? "开启" : "关闭" }}
                </el-tag
                >
            </el-descriptions-item>

            <el-descriptions-item
                    v-if="dataResolver.flag"
                    label="创建时间"
                    align="center"
            >
                <div>{{ dataResolver.data.createdAt }}</div>
            </el-descriptions-item>

            <el-descriptions-item
                    v-if="dataResolver.flag"
                    label="更新时间"
                    align="center"
            >
                <div>{{ dataResolver.data.updatedAt }}</div>
            </el-descriptions-item>


        </el-descriptions>

        <div style="width: 100%; height: 80%;" v-if="dataResolver.flag">
            <div style="width: calc(100% - 40px); margin: 20px">
                <span>解析器属性</span>
            </div>

            <v-ace-editor
                    style="width: 100%; height: 20vh; font-size: 16px; border: 1px solid"
                    v-model:value="dataResolver.data.resolverCode"
                    lang="javascript"
                    theme="monokai"
                    :options="options"
            />

            <div
                    style="
          width: calc(100% - 40px);
          margin: 20px;
          display: flex;
          justify-content: space-between;
        "
            >
                <span>测试数据</span>
                <el-button type="primary" @click="test">测试</el-button>
            </div>

            <v-ace-editor
                    style="width: 100%; height: 15vh; font-size: 16px; border: 1px solid"
                    v-model:value="testParams.inputData"
                    lang="json"
                    theme="monokai"
                    :options="options"
            />

            <div style="width: calc(100% - 40px); margin: 20px">
                <span>返回结果</span>
            </div>

            <v-ace-editor
                    style="width: 100%; height: 15vh; font-size: 16px; border: 1px solid"
                    v-model:value="testResult"
                    lang="json"
                    theme="monokai"
                    :options="options"
            />
        </div>
    </el-scrollbar>

    <el-dialog
            v-model="dialog.show"
            draggable
            width="60vw"
            style="display: flex; flex-direction: column"
    >
        <template #header>
            <h3
                    style="
          width: 100%;
          text-align: center;
          margin: 0;
          border: 0;
          padding: 0;
        "
            >
                {{ dialog.title }}
            </h3>
        </template>
        <el-form :model="dialog.form" label-width="120px" ref="dialogForm">
            <el-form-item label="解析名称" prop="name">
                <el-input
                        v-model="dialog.form.name"
                        placeholder="请输入解析名称（填写项目名称）"
                />
            </el-form-item>
            <el-form-item v-if="isShowTempSelect" label="协议选择" prop="status">
                <el-select
                        v-model="tempSelectValue"
                        placeholder="请选择协议类型"
                        @change="tempChange"
                >
                    <el-option v-for="(item,i) in tempList" :key="i" :label="item.name" :value="item"/>
                </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-switch
                        v-model="dialog.form.status"
                        :active-text="dialog.form.status ? '开启' : '关闭'"
                ></el-switch>
            </el-form-item>

            

            <el-form-item label="解析代码" prop="resolverCode">
                <v-ace-editor
                        style="width: 100%; height: 55vh; font-size: 16px; border: 1px solid"
                        v-model:value="dialog.form.resolverCode"
                        lang="javascript"
                        theme="monokai"
                        :options="options"
                />
            </el-form-item>
        </el-form>

        <template #footer>
      <span>
        <el-button @click="dialog.show = false">取消</el-button>
        <el-button type="primary" @click="addOrUpdateDataResolver">
          确定
        </el-button>
      </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import {
    addDataResolverAPI,
    collectTaskDebug,
    getDataResolverAPI,
    updateDataResolverAPI,
    type DataResolver,
    type DataResolverDTO,
    type DebugDecoderParams,
} from "@/api/solutionService";
import type {CollectTask} from "@/model/group";
import {watch, reactive, ref} from "vue";
import {Plus, Edit} from "@element-plus/icons-vue";
import {VAceEditor} from "vue3-ace-editor";
import "@/assets/aceConfig";
import {Ace} from "ace-builds";
import {ElMessage} from "element-plus";
import {getListAPI} from "@/api/temp"

defineOptions({
    name: "ResolverView", // 解析器
});

const {data} = defineProps<{
    data: CollectTask;
}>();

watch(
    () => data,
    () => {
        getDataResolver();
    }
);

const options: Partial<Ace.EditorOptions> = reactive({
    useWorker: true, // 启用语法检查,必须为true
    enableBasicAutocompletion: true, // 自动补全
    enableLiveAutocompletion: true, // 智能补全
    enableSnippets: true, // 启用代码段
    showPrintMargin: false, // 去掉灰色的线，printMarginColumn
    highlightActiveLine: true, // 高亮行
    highlightSelectedWord: true, // 高亮选中的字符
    tabSize: 4, // tab锁进字符
    fontSize: 14, // 设置字号
    wrap: false, // 是否换行
    readonly: false, // 是否可编辑
    // minLines: 10, // 最小行数，minLines和maxLines同时设置之后，可以不用给editor再设置高度
    // maxLines: 50, // 最大行数
});

/** 解析器弹窗 */
const dialog = ref<{
    show: boolean;
    title: string;
    loading: boolean;
    form: DataResolverDTO | DataResolver;
}>({
    show: false,
    title: "新增解析器",
    loading: false,
    form: {
        status: false,
        remark: "",
        collectTaskId: 0,
        resolverCode: "",
    },
});

/** 解析器展示 */
const dataResolver = ref({
    data: {
        status: false,
        remark: "",
        collectTaskId: 0,
        resolverCode: "",
        id: 0,
        createdAt: "",
        updatedAt: "",
        name:""
    },
    flag: false, // 判断是否有数据
    loading: false,
});

/**
 * 获取解析器数据
 */
async function getDataResolver() {
    // dataResolver.value.loading = true;
    const res = await getDataResolverAPI(data.id!).finally(() => {
        dataResolver.value.loading = false;
    });
    if (res.data != null) {
        dataResolver.value.data = res.data;
        dataResolver.value.flag = true;
    } else {
        dataResolver.value.flag = false;
    }
}

/**
 * 打开解析器弹窗，根据数据状态判断标题和表单内容。
 */
//解析器模板列表
const tempList = ref<any[]>([{code: "", name: "自定义"}])
const isShowTempSelect = ref(false)
//模板选择器展示
const tempSelectValue = ref("")

async function openDialog() {
    // 判断是否有数据 true 有修改 false 没有新增
    if (dataResolver.value.flag) {
        isShowTempSelect.value = false
        dialog.value.title = "修改解析协议";
        dialog.value.form = {...dataResolver.value.data};
    } else {
        dialog.value.title = "新增解析协议";
        isShowTempSelect.value = true
        const res = await getListAPI({
            pageSize: 1000,
            pageNum: 1,
            type: 1,
        });
        if (res.data.list !== null) {
            tempList.value = tempList.value.concat(res.data.list);
        }
        dialog.value.form = {
            status: false,
            remark: "",
            collectTaskId: data.id!,
            resolverCode: "",
        };
    }
    dialog.value.show = true;
}

/**
 * 新增或修改解析器
 */
async function addOrUpdateDataResolver() {
    dialog.value.loading = true;
    const fun = dataResolver.value.flag
        ? updateDataResolverAPI
        : addDataResolverAPI;
    // @ts-ignore
    const res = await fun(dialog.value.form).finally(() => {
        dialog.value.loading = false;
    });

    // @ts-ignore
    if (res.code === 200) {
        ElMessage.success(dataResolver.value.flag ? "修改成功" : "新增成功");
    }else {
        ElMessage.warning(res.data);
        return;
    }
    getDataResolver();
    dialog.value.show = false;
}

/** 解析器测试参数 */
const testParams = ref<DebugDecoderParams>({
    collectTaskId: 0,
    inputData: "",
});

/** 解析器测试响应结果 */
const testResult = ref();

/**
 * 测试方法
 */
async function test() {
    testParams.value.collectTaskId = data.id!;
    const res = await collectTaskDebug(testParams.value);
    testResult.value = res.data;
}

/**
 * 模板列表change事件
 */
function tempChange(val: string) {
    tempSelectValue.value = val.name
    dialog.value.form.resolverCode = val.code
}


</script>

<style scoped></style>
